package com.dingreading.cloud.app.service.impl;

import com.dingreading.cloud.app.entity.StoreAndroidLocation;
import com.dingreading.cloud.app.entity.table.StoreAndroidLocationTableDef;
import com.dingreading.cloud.app.mapper.StoreAndroidLocationMapper;
import com.dingreading.cloud.app.service.StoreAndroidLocationService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class StoreAndroidLocationServiceImpl extends BaseServiceImpl<StoreAndroidLocationMapper, StoreAndroidLocation, StoreAndroidLocationTableDef> implements StoreAndroidLocationService {

    @Override
    protected StoreAndroidLocationTableDef getTable() {
        return StoreAndroidLocationTableDef.storeAndroidLocation;
    }

    @Override
    public long haveLocationInfo(String storeUid, String deviceId, String ymd, String address, String lng, String lat) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid))
                .and(table.deviceId.eq(deviceId))
                .and(table.address.eq(address))
                .and(table.lng.eq(lng))
                .and(table.lat.eq(lat))
                .and(table.addTime.likeLeft(ymd));
        return getMapper().selectCountByCondition(condition);
    }

    @Override
    public void updateInfo(String storeUid, String storeName, String deviceId, String ymd, String ip) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid))
                .and(table.deviceId.eq(deviceId))
                .and(table.addTime.likeLeft(ymd));

        UpdateChain.of(StoreAndroidLocation.class)
                .set(table.storeName, storeName)
                .set(table.ip, ip)
                .where(condition)
                .update();
    }

    @Override
    public List<Long> getNearProtects(String storeUid, String deviceId, String ymd, String longitudeMin, String longitudeMax,
                                      String latitudeMin, String latitudeMax) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.storeUid.eq(storeUid))
                .and(table.deviceId.eq(deviceId))
                .and(table.addTime.likeLeft(ymd))
                .and(table.lat.between(latitudeMin, latitudeMax))
                .and(table.lng.between(longitudeMin, longitudeMax));

        QueryWrapper wrapper = QueryWrapper.create()
                .select(table.id)
                .from(table)
                .where(condition);

        return getMapper().selectListByQueryAs(wrapper, Long.class);
    }

}
